﻿using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
using Oracle.ManagedDataAccess.Client;
using Microsoft.AspNetCore.Http;
using Simple.Services.System;
using Simple.Services.System.QHSEUser.Models;
using Simple.Services.System.QHSEViolationCategory.Models;
using System.Xml.Linq;

namespace Simple.Services;

public class QHSEDictionaryService
{
    private readonly SimpleDbContext _context;
    private readonly CacheService _cacheService;
    public QHSEDictionaryService(SimpleDbContext context, CacheService cacheService)
    {
        _context = context;
        _cacheService = cacheService;
    }
    public async Task<List<QHSEDictionaryModel>> GetAsync()
    {
        var dictionaries = await _context.Set<QHSESysDictionary>().ToListAsync();
        return MapperHelper.Map<List<QHSEDictionaryModel>>(dictionaries);
    }
    public async Task<string> GetCodeByItemAsync(string item)
    {
        var dic = await _context.Set<QHSESysDictionary>().AsNoTracking().Where(u=>u.Item.Equals(item)).Select(u=>u.Code).FirstOrDefaultAsync();
        return dic;
    }
    public async Task<Dictionary<string, string>> GetDictionaryByItemAsync()
    {
        var dictionary = await _context.Set<QHSESysDictionary>()
            .Where(u => u.Item != "其他")
            .Where(u => u.ParentId != "40")
            .AsNoTracking()
            .Select(d => new { d.Item, d.Code }) // 只查询 Item 和 Code 字段
            .ToDictionaryAsync(d => d.Item, d => d.Code);
        return dictionary;
    }
    public async Task<PageResultModel<QHSEDictionaryModel>> GetPageAsync(QHSEDictionaryPageInputModel input)
    {
        var result = new PageResultModel<QHSEDictionaryModel>();
        var query = _context.Set<QHSESysDictionary>().AsNoTracking().AsQueryable();

        if (!string.IsNullOrEmpty(input.Code))
        {
            query = query.Where(u => EF.Functions.Like(u.Code, $"%{input.Code}%"));

        }
        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        query = query.OrderBy(u => u.Code).Page(input.PageNo, input.PageSize);
        var dictionaries= await query.ToListAsync();
        result.Rows = MapperHelper.Map<List<QHSEDictionaryModel>>(dictionaries);

        result.SetPage(input);
        result.CountTotalPage();

        return result;
    }
    public async Task<PageResultModel<QHSEDictionaryModel>> GetIndexPageAsync(PageInputModel page)
    {
        var result = new PageResultModel<QHSEDictionaryModel>();
        var query = _context.Set<QHSESysDictionary>().AsNoTracking().AsQueryable();

        query = query.Where(u => u.ParentId == "0");
        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        query = query.OrderBy(u => u.Code).Page(page.PageNo,page.PageSize);
        var dictionaries = await query.ToListAsync();
        result.Rows = MapperHelper.Map<List<QHSEDictionaryModel>>(dictionaries);
        result.SetPage(page);
        result.CountTotalPage();

        return result;
    }

    public async Task<int> AddAsync(QHSEDictionaryModel model)
    {
        // 查询数据库，找到具有相同 ParentId 的字典
        var matchingDictionaries = await _context.Set<QHSESysDictionary>()
            .Where(d => d.ParentId == model.ParentId)
            .ToListAsync(); // Fetch the data from the database
        var parent = _context.Set<QHSESysDictionary>()
            .Where(d => d.Id == model.ParentId)
            .FirstOrDefault();
        if (matchingDictionaries.Count == 0 && parent!=null)
        {
            model.Code =parent.Code + "0001";
        }
        else
        {
            // 将数据库中的字典的 Code 转换为整数进行比较
            var maxCode = matchingDictionaries
                .Select(d => ParseCodeOrDefault(d.Code))
                .Max();

            // 将新字典的 Code 设置为最大 Code + 1
            model.Code = (maxCode + 1).ToString("D4"); // Format as four-digit string
        }

        // 使用映射将 QHSEDictionaryModel 转换为 QHSESysDictionary
        var dictionary = MapperHelper.Map<QHSESysDictionary>(model);

        // 将新字典添加到上下文
        await _context.AddAsync(dictionary);
        await _cacheService.ClearDictionaryyCacheAsync();
        // 返回保存更改的结果
        return await _context.SaveChangesAsync();
    }

    private int ParseCodeOrDefault(string? code)
    {
        // 尝试将 'Code' 解析为整数，失败时返回默认值
        return int.TryParse(code, out int codeValue) ? codeValue : 0;
    }


    public async Task<int> UpdateAsync(QHSEDictionaryModel model)
    {
        if (await _context.Set<QHSESysDictionary>().AnyAsync(d => d.Id != model.Id && d.Code == model.Code))
        {
            throw AppResultException.Status409Conflict("存在相同编码");
        }
        var dictionary = await _context.Set<QHSESysDictionary>()
            .Where(d => model.Id == d.Id)
            .FirstOrDefaultAsync();

        if (dictionary == null)
        {
            throw AppResultException.Status404NotFound("找不到字典，更新失败");
        }

        MapperHelper.Map<QHSEDictionaryModel, QHSESysDictionary>(model, dictionary);
        _context.Update(dictionary);
        int ret = await _context.SaveChangesAsync();

        if (ret == 0)
        {
            throw AppResultException.Status200OK("更新记录数为0");
        }
        await _cacheService.ClearDictionaryyCacheAsync();
        return ret;
    }
    public async Task<int> DeleteAsync(IEnumerable<string> ids)
    {
        var dictionaries = await _context.Set<QHSESysDictionary>()
            .Where(d => ids.Contains(d.Id))
            .ToListAsync();

        _context.RemoveRange(dictionaries);
        await _cacheService.ClearDictionaryyCacheAsync();
        return await _context.SaveChangesAsync();
    }

    public async Task<List<QHSEDictionaryModel>> GetDictionaryAsync(string code)
    {
        var result = await _cacheService.GetQHSEDictionaryuAsync(code);
        if (result.Count == 0)
        {
            var query = _context.Set<QHSESysDictionary>().AsNoTracking().AsQueryable();

            if (!string.IsNullOrEmpty(code))
            {
                query = query.Where(u => EF.Functions.Like(u.Code, $"{code}%")).Where(u => u.Code != code);

            }
            var list = await query.OrderBy(u=>u.OrderNo).ToListAsync();
            var models = MapperHelper.Map<List<QHSEDictionaryModel>>(list);
            await _cacheService.SetQHSEDictionaryuAsync(models,code);
            return models;
        }
        else
        {
            var zzj = "sb";
        }
        return result;
    }
    public async Task<List<QHSEDictionaryModel>> GetDictionaryAsync(string code,SimpleDbContext context)
    {
        var result = await _cacheService.GetQHSEDictionaryuAsync(code);
        if (result.Count == 0)
        {
            var query = context.Set<QHSESysDictionary>().AsNoTracking().AsQueryable();

            if (!string.IsNullOrEmpty(code))
            {
                query = query.Where(u => EF.Functions.Like(u.Code, $"{code}%")).Where(u => u.Code != code);

            }
            var list = await query.OrderBy(u => u.OrderNo).ToListAsync();
            var models = MapperHelper.Map<List<QHSEDictionaryModel>>(list);
            await _cacheService.SetQHSEDictionaryuAsync(models, code);
            return models;
        }
        else
        {
            var zzj = "sb";
        }
        return result;
    }
    public async Task<PageResultModel<QHSEDictionaryModel>> GetDictionaryPageAsync(PageInputModel page)
    {
        var resultPage = new PageResultModel<QHSEDictionaryModel>();
            var query = _context.Set<QHSESysDictionary>().AsNoTracking().AsQueryable();

            if (!string.IsNullOrEmpty(page.Code))
            {
                query = query.Where(u => EF.Functions.Like(u.Code, $"{page.Code}%")).Where(u => u.Code != page.Code);

            }

            resultPage.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.OrderBy(u => u.Code).Page(page.PageNo,page.PageSize);
            var dictionaries = await query.ToListAsync();
            resultPage.Rows = MapperHelper.Map<List<QHSEDictionaryModel>>(dictionaries);
            resultPage.SetPage(page);
            resultPage.CountTotalPage();
            return resultPage;
     }

    public async Task<List<DictionaryTreeNodeModel>> GetTreeAsync(QHSEDictionaryTreeInputModel input)
    {
        var query = _context.Set<QHSESysDictionary>().AsNoTracking().AsQueryable();

        // 根据条件查询
        if (!string.IsNullOrEmpty(input.Name))
        {
            query = query.Where(m => EF.Functions.Like(m.Item, $"%{input.Name}%"));
        }

        // 排序
        query = query.OrderBy(m => m.OrderNo);

        var menus = await query.ToListAsync();
        var nodes = MapperHelper.Map<List<DictionaryTreeNodeModel>>(menus);

        var builder = DictionaryTreeNodeModel.CreateBuilder(nodes, "17");
        return builder.Build();
    }
    public async Task<List<DictionaryTreeNodeModel>> GetGWTreeAsync(QHSEDictionaryTreeInputModel input)
    {
        var query = _context.Set<QHSESysDictionary>().AsQueryable();

        // 根据条件查询
        if (!string.IsNullOrEmpty(input.Name))
        {
            query = query.Where(m => EF.Functions.Like(m.Item, $"%{input.Name}%"));
        }

        // 排序
        query = query.OrderBy(m => m.OrderNo);

        var menus = await query.ToListAsync();
        var nodes = MapperHelper.Map<List<DictionaryTreeNodeModel>>(menus);

        var builder = DictionaryTreeNodeModel.CreateBuilder(nodes, "65");
        return builder.Build();
    }

    public async Task<List<AntTreeNode>> GetGWDTreeAsync()
    {
        var query = _context.Set<QHSESysDictionary>().AsQueryable();

        var gws = await query
            .OrderBy(m => m.OrderNo)
            .ToListAsync();
        List<TreeNode> nodes = MapperHelper.Map<List<TreeNode>>(gws);

        var builder = AntTreeNode.CreateBuilder(nodes,"65");
        return builder.Build();
    }
    public async Task<List<AntTreeNode>> GetQYTreeAsync()
    {
        var query = _context.Set<QHSESysDictionary>().AsQueryable();

        var gws = await query
            .OrderBy(m => m.OrderNo)
            .ToListAsync();
        List<TreeNode> nodes = MapperHelper.Map<List<TreeNode>>(gws);

        var builder = AntTreeNode.CreateBuilder(nodes, "17");
        return builder.Build();
    }
}
